//
//  ST_RecommendPeculiarityController.swift
//  btvideo
//
//  Created by mac on 2020/6/2.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import MJRefresh
import SwiftyJSON
import SwiftyUserDefaults
import RxSwift

//推荐特质 瀑布流 -Controller
class ST_RecommendPeculiarityController: UIViewController {
    
    static let shared = ST_RecommendPeculiarityController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.refresh_data()
        })
        
        binding()
        
    }
    
    private func binding(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(showed_noti_handle(noti:)), name: Notification.Name.showedSomeOne, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(remove_some_one_hanlde(noti:)), name: Notification.Name.ban_somebody, object: nil)
        
        
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
        
        SCComponets.location_component.loc_pushed_observer.observe(on: MainScheduler.instance).subscribe(onNext: { v in
            
            if v != nil {
                self.refresh_data()
                
                print("订阅到 定位更新成功！！-- ST_RecommendPeculiarityController")
            }
        }).disposed(by: rx.disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f != true{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
        //        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.group_id.string == id}) else{
            return
        }
        
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
        
    }
    
    //    MARk: - scan UI
    fileprivate func stop_scan_view(){
        
        scan_root_view.isHidden = true
        scan_animate_view.stop()
        
    }
    
    func play_scan_view(){
        
        if scan_root_view.superview == nil{
            view.insertSubview(scan_root_view, aboveSubview: collectionView)
            scan_root_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            
            scan_root_view.addSubview(scan_animate_view)
            scan_animate_view.snp.makeConstraints { (make) in
                make.width.height.equalTo(50/375.0*ScreenWidth)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
        }
        scan_root_view.isHidden = false
        scan_animate_view.play()
    }
    
    
    
    fileprivate lazy var scan_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "homeSearchAnimation", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
    
    @objc func remove_some_one_hanlde(noti:Notification){
        
        //         ["accid": self.accid,"likeOption":true]
        let json = JSON.init(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        self.data_array.removeFirst(where: {$0.accid == accid})
        
        self.collectionView.reloadData()
        
    }
    
    @objc fileprivate func showed_noti_handle(noti:Notification){
        
        
        //        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.accid == id}) else{
            return
        }
        
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isAttention = isThumbUp
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
        
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //    MARK: SetUp Data
    func waiting_for_fetch_boot() {
        
        self.play_scan_view()
        
    }

    
    func clear_data(){
        
        currentPage = 0
        
        self.data_array.removeAll()
        self.collectionView.reloadData()
        
        pause_video()
    }
    
    @objc  func refresh_data(){
        
        self.clear_data()
        
        self.request_data()
        
        ST_RecommendVideoDataAdapter.shared.refresh_data()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate var filterSEX:ST_SEX?
    
    fileprivate lazy var last_filter_face_status:Bool = {
        return OnlyLookFaceDetected
    }()
    
    
    fileprivate lazy var last_filter_neighbor:Bool = {
        return OnlyLookNeighbor
    }()
    
    func filter_remote_data(sex:ST_SEX){
        
        if let last = filterSEX,last.rawValue == sex.rawValue,last_filter_face_status == OnlyLookFaceDetected,last_filter_neighbor == OnlyLookNeighbor{
            return
        }
        
        clear_data()
        
        filterSEX = sex
        
        self.request_data()
        
    }
    
    @objc fileprivate func request_data(){
        
        if currentPage == 0{
            self.play_scan_view()
        }
        
        currentPage += 1
        
        var param = ["page":currentPage,
                     "size":20] as [String : Any]
        
        if let sex = filterSEX{
            
            param.updateValue(sex.rawValue, forKey: "feature_type")
        }
        
        if OnlyLookFaceDetected{
            
            param.updateValue(3, forKey: "face_state")
        }
        
        if OnlyLookNeighbor{
            
            param.updateValue(1, forKey: "is_same_city")
        }
        
        self.last_filter_face_status = OnlyLookFaceDetected
        
        self.last_filter_neighbor = OnlyLookNeighbor
        
        
        JVrequest(PH.recommendFeedApi,parameters:param, success: { (json) in
            
            print("首页推荐特质的数据：",json["data"])
            
            
            let data = json["data"]
            
            let list = data["list"].arrayValue
            
            let aArray = list.map { (itemJson) -> ST_TraitOfOperatCellModel in
                let m = ST_TraitOfOperatCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
            
            //            let aArray = ST_ShowTraitCellModel.describe(json_array: list)
            
            if self.currentPage == 1{
                self.data_array = aArray
            }else{
                self.data_array += aArray
            }
            
            var addedDict = [String: Bool]()
            
            self.data_array = self.data_array.filter {
                addedDict.updateValue(true, forKey: $0.featureContentId.string) == nil
            }
            
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
            self.stop_scan_view()
            
            self.load_more_option_style(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
    
    
    
    //    MARK:- Player View
    
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
    //    MARK:- properties
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = 15
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 10, bottom: BTSafeAreaBottom + 60, right: 10)
        controlLayout.header_height = 118
        return controlLayout
    }()
    
    /**
     首页展示人的 collectionView
     */
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_TraitOfOperatCell.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_RecommendPecHeaderView.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    //    fileprivate var last_content_offset: CGFloat = 0
    
    //    MARK:- Collection  Data Source
    fileprivate lazy var data_array = [ST_TraitOfOperatCellModel]()
    
    //    MARK:- Play Operation
    fileprivate var current_play_index_path:IndexPath?
    
    
    fileprivate func play(indexPath:IndexPath){
        
        pause_video()
        
        if TopmostViewController() != self{
            return
        }
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_ShowTraitCell , let dataItem = data_array[safe:indexPath.item] else{return}
        
        if dataItem.type != .video{
            
            return
        }
        
        cell.contentView.addSubview(playerView)
        
        let rect = cell.picutreframe_in_content_view()
        
        playerView.frame = rect
        
        
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: dataItem.imageUrl, videoUrl: dataItem.videoUrl, width: dataItem.width, height: dataItem.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in collectionView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            if let cell = item as? ST_ShowTraitCell,cell.model.type == .video{
                
                if let playIdx = collectionView.indexPath(for: cell){
                    
                    if let last = foundIndex,last.item < playIdx.item{
                        continue
                    }
                    
                    let rectInScreen = collectionView.convert(cell.frame, to: nil)
                    
                    let intersect = containerRect.intersection(rectInScreen)
                    
                    let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                    //               小于 70% 换下一个哈
                    if percent < 0.8{
                        continue
                    }
                    
                    foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
            
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
            //               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
            // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        print("cell视频---切换到另外一个Item:",foundIndex?.item ?? "🈚️")
        
        return foundIndex
    }
    
    
    
    
    
}



extension ST_RecommendPeculiarityController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        if let last = current_play_index_path,last.row == indexPath.row{
            self.pause_video()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        cell.max_content_number_of_lines = 2
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        self.present_detail(indexPath: indexPath)
        
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let v = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_RecommendPecHeaderView.self, for: indexPath)
        
        return v
        
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        let a = self.data_array.count - indexPath.row
        
        
        if a <= 8 {
            
            self.collectionView.mj_footer?.beginRefreshing()
            
        }
    }
    
    //    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
            
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
        
        
        // update the new position acquired
        //       self.last_content_offset = scrollView.contentOffset.y
        
        
        
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        scrollviewdidEndScroll(scrollView)
        
    }
    
    //    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}



//MARK: - 跳转详情
extension ST_RecommendPeculiarityController{
    
    
    func present_detail(indexPath:IndexPath) {
        
        
        guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol else{
            return
        }
        
        let model = data_array[indexPath.row]
        
        //      当前正在播放 并且不是当前点击这个
        if current_play_index_path != indexPath{
            
            pause_video()
            //            1视频 2 图片
            if model.type == .video{
                
                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
            }else{
                
                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
                
            }
            
        }
        
        transition.operationView = self.playerView
        
        let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
        
        playerView.present_start_rect = rectInScreen
        playerView.present_start_idx = indexPath
        playerView.fromeController = self
        
        let item = model
        
        ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, remark: item.sign, firstPhotoSize: CGSize.init(width: item.width, height: item.height), transition: transition, presentRootController: self)
        
    }
    
    
    
}


extension ST_RecommendPeculiarityController:ST_PairsTransitionProtocol{
    
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}
